//
//  StatusPictureView.swift
//  SinaWeibo
//
//  Created by gaoliang on 15/11/15.
//  Copyright © 2015年 gaoliang. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let PictureCellID = "PictureCellID"
private let PictureCellMargin: CGFloat = 5
class StatusPictureView: UICollectionView {

    var imageURLs: [NSURL]? {
        didSet {
//            print(imageURLs)
            
            // 刷新数据
            reloadData()
            
            let viewSize = self.calceViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            testLable.text = "\(imageURLs?.count ?? 0)"
        }
    }
    
    // 计算配图的大小
    private func calceViewSize() -> CGSize {
        // 获取配图最大宽度
        let colum: CGFloat = 3.000000000001
        let maxWidth = screenW - 2 * StatusCellMargin
        //  单个图片宽度
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        let layout = self.collectionViewLayout as? UICollectionViewFlowLayout
        layout?.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        let imageCount = imageURLs?.count ?? 0
        if imageCount == 0 {
            return CGSizeZero
        }
        // 单张图片
        if imageCount == 1 {
            // 后续再处理 单张图片
            // 获得单张被缓存的图片
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key)
            
            let imageSize = image.size
            layout?.itemSize = imageSize
            return imageSize
        }
        
        // 四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            return CGSizeMake(w, w)
        }
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = row * itemWidth + (row - 1) * PictureCellMargin
        return CGSize(width: w, height: h)
    }
    
    //MARK: 3.重写父类的构造方法 调用设置UI
    init() {
        let layout = UICollectionViewFlowLayout()
        // 设置 layout
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        // 注册
        registerClass(Picturecell.self, forCellWithReuseIdentifier: PictureCellID)
        // 设置代理
        dataSource = self
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 2.设置 UI
    private func setupUI() {
        backgroundColor = UIColor.randomColor()
        addSubview(testLable)
        testLable.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    //MARK: 1. 懒加载所有子控件
    private lazy var testLable: UILabel = {
        let l = UILabel()
        l.font = UIFont.systemFontOfSize(25)
        l.textColor = UIColor.redColor()
        l.sizeToFit()
        return l
    }()
}

//MARK:实现必选的数据源方法
extension StatusPictureView: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellID, forIndexPath: indexPath) as! Picturecell
        cell.url = imageURLs![indexPath.item]
        return cell
        
    }
}
class Picturecell: UICollectionViewCell {
    
    var url: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(url, placeholderImage: nil)
        }
    }
    //MARK: 3.重写父类的构造方法 调用设置UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 2.设置 UI
    private func setupUI() {
    contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            // 与四周的就间距
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    //MARK: 1. 懒加载所有子控件
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        // 设置图片显示样式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        // 手写代码 必须自己手动添加 裁减
        iv.clipsToBounds = true
        return iv
    }()
}




